﻿using System.Web.Mvc;
using KLS.PPDS.ApplicationService.Manager;

namespace KLS.PPDS.Data.Database
{
    public class TransactionAttribute : ActionFilterAttribute, IExceptionFilter
    {
       
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            DatabaseManager.BeginTransaction();
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);

            if (filterContext.Exception != null && !filterContext.ExceptionHandled)
            {
                DatabaseManager.RollbackTransaction();
            }
            else
            {
                DatabaseManager.CommitTransaction();
            }
        }

        #region IExceptionFilter Members

        public void OnException(ExceptionContext filterContext)
        {
            DatabaseManager.RollbackTransaction();
        }

        #endregion
    }
}
